package com.hsq.androidproject.ui.find_fragment.taolun;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.lenovo.androidproject3.R;
import com.hsq.androidproject.adapter.ListViewImgsAdapter;
import com.hsq.androidproject.adapter.MyListViewCommentAdapter;
import com.hsq.androidproject.db.DBHelper;
import com.hsq.androidproject.entity.bd_entity.TopicsLike;
import com.hsq.androidproject.entity.find.FindComment;
import com.hsq.androidproject.entity.find.FindPersonOne;
import com.hsq.androidproject.utils.DensityUtil;
import com.hsq.androidproject.utils.OkHttpClientManager;
import com.hsq.androidproject.utils.SelfDialog;
import com.hsq.androidproject.utils.glide.GlideCircleTransform;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.okhttp.Request;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ShowTopicsOneActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener {

    private String userName = "peng";      /////获取

    private TextView tv_topTitle;
    private TextView tv_userNick, tv_time, tv_title, tv_content;       /////作者名字  时间   发布标题  发布内容
    private ImageView iv_img;
    private ListView mListView;
    private TextView tv_commentCount;       ////评论数
    private int tid;
    private RadioButton rb_early, rb_new;
    private RadioGroup rg_group;
    private PullToRefreshListView pl_listview;
    //当前页数
    private int curPage = 1;
    private String path;
    private MyListViewCommentAdapter adapter;
    private List<FindComment.PostsBean> postsBean;
    private List<FindComment.PostsBean> postsBean1;
    private ScrollView sv_view;
    private ImageView iv_likeCount, iv_none; ////喜欢      没有评论数据
    private TextView tv_likeCount, tv_none; ////喜欢           没有评论数据
    private DBHelper dbHelper;
    private TopicsLike topicsLike;
    private LinearLayout ll_comment1;
    private RelativeLayout ll_comment2;
    private EditText et_comment;
    private TextView et_commentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_topics_one);
        initView();
        Intent intent = getIntent();       //////from  MyListViewFindTopicsAdapter
        tid = intent.getIntExtra("tid", 0);
        String title = intent.getStringExtra("title");
        int commentCount = intent.getIntExtra("commentCount", 0);
        tv_topTitle.setText(title);
        tv_commentCount.setText("全部评论： " + commentCount);
        if (commentCount == 0) {
            iv_none.setVisibility(View.VISIBLE);
            tv_none.setVisibility(View.VISIBLE);
        } else {
            iv_none.setVisibility(View.GONE);
            tv_none.setVisibility(View.GONE);
        }
        topicsLike = new TopicsLike(tv_title.getText().toString(), userName);
        if (dbHelper.isExistT(topicsLike)) {
            iv_likeCount.setImageResource(R.drawable.big_like_icon_highlight);
            tv_likeCount.setTextColor(Color.parseColor("#ED4C4B"));
        } else {
            iv_likeCount.setImageResource(R.drawable.big_like_icon);
            tv_likeCount.setTextColor(Color.parseColor("#000000"));
        }
        rg_group.setOnCheckedChangeListener(this);
        /*个人信息*/
        addDataPerson();
        addData("early");

        sv_view.setOnTouchListener(new View.OnTouchListener() { ////加载更多  page+++
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 判断scrollview 滑动到底部  // scrollY 的值和子view的高度一样，这人物滑动到了底部
                if (sv_view.getChildAt(0).getHeight() - sv_view.getHeight()
                        == sv_view.getScrollY()) {
                    if (rb_early.getTextColors().equals("#fe5793")) {
                        requestData("early", curPage + 1);
                    } else {
                        requestData("new", curPage + 1);
                    }
                }
                return false;
            }
        });
        /////评论
        pl_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {  /////回复评论获取用户信息
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                /*类转换异常ClassCastException FindMineTL.TopicsBean  */
                FindComment.PostsBean messages = (FindComment.PostsBean) parent.getItemAtPosition(position);
                String username = messages.getUserNick();
                int floor = messages.getFloor();
                et_commentUser.setVisibility(View.VISIBLE);
                et_commentUser.setText("回复" + floor + "楼@" + username);
                ///Toast.makeText(ShowTopicsOneActivity.this, "" + username, Toast.LENGTH_SHORT).show();
            }
        });
        ll_comment1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_comment1.setVisibility(View.GONE);
                ll_comment2.setVisibility(View.VISIBLE);
                et_commentUser.setVisibility(View.GONE);
            }
        });
    }

    private void requestData(String type, final int curPage) {
        if (type.equals("early")) { /*评论   最早*/
            path = "http://api.hanju.koudaibaobao.com/bbs/api/forum/posts?tid=" + tid + "&page=" + curPage;

        } else if (type.equals("new")) {  /*评论   最新*/
            path = "http://api.hanju.koudaibaobao.com/bbs/api/forum/posts?tid=" + tid + "&page=" + curPage + "&sort=1";
        }

        if (curPage == 1) {
            pl_listview.onRefreshComplete();

        } else {
            OkHttpClientManager.getAsyn(path, new OkHttpClientManager.ResultCallback<String>() {
                @Override
                public void onError(Request request, Exception e) {
                    Toast.makeText(ShowTopicsOneActivity.this, "出错啦! ", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onResponse(String response) {
                    FindComment findComment = new Gson().fromJson(response, FindComment.class);
                    postsBean1 = findComment.getPosts();    //  得到集合数据
                    for (int i = 0; i < postsBean1.size(); i++) {
                        postsBean.add(postsBean1.get(i));
                    }
                    //page为1 的时候 清理集合 ,否则不清理集合 调用下面的方法
                    int size = postsBean.size();
                    int height = DensityUtil.dip2px(ShowTopicsOneActivity.this, 101 * size);
                    pl_listview.setMinimumHeight(height);
                    adapter.notifyDataSetChanged();
                    pl_listview.onRefreshComplete();  //完成
                }
            });
        }
    }

    public void click_like(View view) {         //////喜欢
        if (dbHelper.isExistT(topicsLike)) {
            iv_likeCount.setImageResource(R.drawable.big_like_icon);
            tv_likeCount.setTextColor(Color.parseColor("#000000"));
            dbHelper.deleteTopicsLikeByNameAndUserName(topicsLike);
        } else {
            iv_likeCount.setImageResource(R.drawable.big_like_icon_highlight);
            tv_likeCount.setTextColor(Color.parseColor("#ED4C4B"));
            dbHelper.insertTopicsLike(topicsLike);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_early:
                rb_early.setTextColor(Color.parseColor("#fe5793"));
                rb_new.setTextColor(Color.parseColor("#000000"));
                addData("early");
                break;
            case R.id.rb_new:
                rb_early.setTextColor(Color.parseColor("#000000"));
                rb_new.setTextColor(Color.parseColor("#fe5793"));
                addData("new");

                break;
        }
    }

    private void addData(String type) {
        if (type.equals("early")) { /*评论   最早*/
            path = "http://api.hanju.koudaibaobao.com/bbs/api/forum/posts?tid=" + tid + "&page=" + curPage;

        } else if (type.equals("new")) {  /*评论   最新*/
            path = "http://api.hanju.koudaibaobao.com/bbs/api/forum/posts?tid=" + tid + "&page=" + curPage + "&sort=1";
        }
        OkHttpClientManager.getAsyn(path, new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {
                Toast.makeText(ShowTopicsOneActivity.this, "出错啦！", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response) {
                FindComment findComment = new Gson().fromJson(response, FindComment.class);
                postsBean = findComment.getPosts();
                int size = findComment.getPosts().size();

                int height = DensityUtil.dip2px(ShowTopicsOneActivity.this, 101 * size);
                pl_listview.setMinimumHeight(height);
                adapter = new MyListViewCommentAdapter(postsBean, ShowTopicsOneActivity.this);
                pl_listview.setAdapter(adapter);
            }
        });
    }

    private void addDataPerson() {
        String path = "http://api.hanju.koudaibaobao.com/bbs/api/forum/topicInfo?tid=" + tid;
        OkHttpClientManager.getAsyn(path, new OkHttpClientManager.ResultCallback<String>() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                FindPersonOne personOne = new Gson().fromJson(response, FindPersonOne.class);
                FindPersonOne.TopicBean topicsBean = personOne.getTopic();

                final String thumb = topicsBean.getUserAvatar();
                Glide.with(ShowTopicsOneActivity.this)
                        .load(thumb)
                        .transform(new GlideCircleTransform(ShowTopicsOneActivity.this))//圆形
                        .into(iv_img);

                final String userNick = topicsBean.getUserNick();
                tv_userNick.setText(userNick);

                long postTime = topicsBean.getLastReplyTime();          ///////postTime 应该是:lastReplyTime
                String time = getTimeFromMillisecond(postTime);

                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                String date = sdf.format(new Date());

                long diff = 0;
                long hours = 0;
                long minutes = 0;
                try {
                    Date d1 = sdf.parse(date);
                    Date d2 = sdf.parse(time);
                    diff = d1.getTime() - d2.getTime();
                    long days = diff / (1000 * 60 * 60 * 24);
                    hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
                    minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);

                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (hours != 0) {///hours + ":" + minutes
                    tv_time.setText(hours + "小时前");
                } else if (hours == 0) {
                    if (minutes > 3) {
                        tv_time.setText(minutes + "分钟前");
                    } else {
                        tv_time.setText("刚刚");
                    }
                }

                tv_title.setText(topicsBean.getTitle());
                tv_content.setText(topicsBean.getContent());
                /////:>>>>>>
                //图片
                try {           /////有的没有photoes
                    List<FindPersonOne.TopicBean.PhotoesBean> photoesBean = topicsBean.getPhotoes();
                    if (photoesBean.equals(null) && photoesBean == null) {
                        mListView = null;
                        mListView.setVisibility(View.GONE);
                    } else {
                        mListView.setVisibility(View.VISIBLE);
                        ListViewImgsAdapter adapter = new ListViewImgsAdapter(ShowTopicsOneActivity.this, photoesBean);
                        mListView.setAdapter(adapter);
                        setListViewHeightBasedOnChildren(mListView);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void initView() {
        dbHelper = new DBHelper(this);
        tv_topTitle = (TextView) findViewById(R.id.tv_topTitle);
        tv_userNick = (TextView) findViewById(R.id.tv_userNick);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_content = (TextView) findViewById(R.id.tv_content);
        iv_img = (ImageView) findViewById(R.id.iv_img);
        tv_commentCount = (TextView) findViewById(R.id.tv_commentCount);
        rb_early = (RadioButton) findViewById(R.id.rb_early);
        rb_new = (RadioButton) findViewById(R.id.rb_new);
        rg_group = (RadioGroup) findViewById(R.id.rg_group);
        sv_view = (ScrollView) findViewById(R.id.sv_view);
        iv_likeCount = (ImageView) findViewById(R.id.iv_likeCount); ////喜欢img
        tv_likeCount = (TextView) findViewById(R.id.tv_likeCount);////喜欢tv
        iv_none = (ImageView) findViewById(R.id.iv_none);   ////没有评论img
        tv_none = (TextView) findViewById(R.id.tv_none);    ////没有评论tv
        ll_comment1 = (LinearLayout) findViewById(R.id.ll_comment1);
        ll_comment2 = (RelativeLayout) findViewById(R.id.ll_comment2);
        et_comment = (EditText) findViewById(R.id.et_comment);
        et_commentUser = (TextView) findViewById(R.id.et_commentUser);

        pl_listview = (PullToRefreshListView) findViewById(R.id.pl_listview);
        pl_listview.setFocusable(false);

        mListView = (ListView) findViewById(R.id.mListView);
        mListView.setFocusable(false);
    }

    public static String getTimeFromMillisecond(Long millisecond) {		/*毫秒转换为时间*/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        Date date = new Date(millisecond);
        String timeStr = simpleDateFormat.format(date);
        return timeStr;
    }

    public void setListViewHeightBasedOnChildren(ListView listView) {
        // 获取ListView对应的Adapter
        ListViewImgsAdapter listAdapter = (ListViewImgsAdapter) listView.getAdapter();
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }

    public void click_back(View view) {
        finish();
    }

    public void click_cancle(View view) {
        ll_comment2.setVisibility(View.GONE);
        ll_comment1.setVisibility(View.VISIBLE);
    }

    public void click_fabu(View view) {
        if (et_comment.getText().toString().equals(null)) {
            Toast.makeText(this, "发布内容不能为空", Toast.LENGTH_SHORT).show();
        } else {
            Handler mHandler = new Handler();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(ShowTopicsOneActivity.this, "您的等级不够，不允许发帖", Toast.LENGTH_SHORT).show();
                    ll_comment2.setVisibility(View.GONE);
                    ll_comment1.setVisibility(View.VISIBLE);
                }
            }, 2000);
        }
    }

    public void click_jubao(View view) {
        SelfDialog selfDialog;
        selfDialog = new SelfDialog(this);
        final SelfDialog finalSelfDialog = selfDialog;
        selfDialog.setYesOnclickListener("确认举报", new SelfDialog.onYesOnclickListener() {
            @Override
            public void onYesClick() {
                Toast.makeText(ShowTopicsOneActivity.this, "举报成功", Toast.LENGTH_SHORT).show();
                finalSelfDialog.dismiss();
            }
        });
        selfDialog.setNoOnclickListener("取消举报", new SelfDialog.onNoOnclickListener() {
            @Override
            public void onNoClick() {
                finalSelfDialog.dismiss();
            }
        });
        selfDialog.show();
    }
}
